package com.xuesaieducation.zshddemo.fragments;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gensee.entity.PingEntity;
import com.gensee.player.OnPlayListener;
import com.gensee.player.Player;
import com.gensee.view.GSVideoView;
import com.xuesaieducation.zshddemo.R;
import com.xuesaieducation.zshddemo.ScreenUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

@SuppressLint("ValidFragment")
public class VideoFragment extends Fragment
{
    @BindView(R.id.layout)
    FrameLayout parent;
    @BindView(R.id.imvideoview)
    GSVideoView mGSViedoView;
    @BindView(R.id.audio_only_holder)
    ImageView audioOnlyHolder;


    @BindView(R.id.toolbar)
    RelativeLayout toolbar;
    @BindView(R.id.exit)
    ImageView exit;
    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.operate)
    FrameLayout operate;

    @BindView(R.id.right_operate)
    RelativeLayout rightOperate;
    @BindView(R.id.hand_up)
    ImageView handUp;
    @BindView(R.id.tx_hand)
    TextView txtHand;
    @BindView(R.id.audio_only)
    ImageView audioOnly;
    @BindView(R.id.full_screen)
    ImageView fullScreen;

    @BindView(R.id.left_operate)
    RelativeLayout leftOperate;
    @BindView(R.id.online_people)
    TextView onlineCount;
    @BindView(R.id.net_type)
    ImageView netType;

    Unbinder unbinder;

    private Player mPlayer;
    private View mView;

    Animation toolbarAppearAnim, toolbarDisappearAnim;
    Animation rightbarAppearAnim, rightbarDisappearAnim;
    Animation leftbarAppearAnim, leftbarDisappearAnim;

    public VideoFragment(Player player)
    {
        this.mPlayer = player;
    }

    private VideoFragListener callback;

    public void setVideoFragListener(VideoFragListener s)
    {
        this.callback = s;
    }

    public interface VideoFragListener
    {
        void onLiveExit();

        void onLiveFullScreenClick();
    }

    Activity mContext;

    @Override
    public void onAttach(Context context)
    {
        super.onAttach(context);
        if (context instanceof Activity)
            mContext = (Activity) context;
        initAnim(context);
    }

    boolean isAnimGoing;
    boolean isOperateVisiable;

    private void initAnim(Context ctx)
    {
        toolbarAppearAnim = AnimationUtils.loadAnimation(ctx, R.anim.anim_top_dowm);
        toolbarAppearAnim.setDuration(350);
        toolbarDisappearAnim = AnimationUtils.loadAnimation(ctx, R.anim.anim_dowm_top);
        toolbarDisappearAnim.setDuration(350);

        rightbarAppearAnim = AnimationUtils.loadAnimation(ctx, R.anim.anim_left_right);
        rightbarAppearAnim.setDuration(350);
        rightbarDisappearAnim = AnimationUtils.loadAnimation(ctx, R.anim.anim_right_left);
        rightbarDisappearAnim.setDuration(350);

        leftbarAppearAnim = AnimationUtils.loadAnimation(ctx, R.anim.anim_left_appear);
        leftbarAppearAnim.setDuration(350);
        leftbarDisappearAnim = AnimationUtils.loadAnimation(ctx, R.anim.anim_left_disappear);
        leftbarDisappearAnim.setDuration(350);

        rightbarAppearAnim.setAnimationListener(new Animation.AnimationListener()
        {
            @Override
            public void onAnimationStart(Animation animation)
            {
                isAnimGoing = true;
            }

            @Override
            public void onAnimationEnd(Animation animation)
            {
                isAnimGoing = false;
                isOperateVisiable = true;
            }

            @Override
            public void onAnimationRepeat(Animation animation)
            {

            }
        });
        rightbarDisappearAnim.setAnimationListener(new Animation.AnimationListener()
        {
            @Override
            public void onAnimationStart(Animation animation)
            {
                isAnimGoing = true;
            }

            @Override
            public void onAnimationEnd(Animation animation)
            {
                isAnimGoing = false;
                isOperateVisiable = false;
                operate.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation)
            {

            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        mView = inflater.inflate(R.layout.imviedo, null);
        return mView;
    }

    int parentPortraitWidth, parentPortraitHeight;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
        unbinder = ButterKnife.bind(this, view);
        onJoin(false);
        mPlayer.setGSVideoView(mGSViedoView);
        parent.post(new Runnable()
        {
            @Override
            public void run()
            {
                parentPortraitWidth = parent.getMeasuredWidth();
                parentPortraitHeight = parent.getMeasuredHeight();
            }
        });
        operate.postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                operate.setVisibility(View.VISIBLE);
                toolbar.startAnimation(toolbarAppearAnim);
                rightOperate.startAnimation(rightbarAppearAnim);
                leftOperate.startAnimation(leftbarAppearAnim);
            }
        }, 1500);
        initIfHasDataBefore();
    }

    private void initIfHasDataBefore()
    {
        onlineCount.setText(String.valueOf(personCount));
        if(!TextUtils.isEmpty(titleStr))
        {
            title.setText(titleStr);
        }
    }

    @Override
    public void onDestroyView()
    {
        super.onDestroyView();
        if (unbinder != null)
            unbinder.unbind();
        mContext = null;
    }

    public void onJoin(boolean isJoined)
    {
//        handUp.setEnabled(isJoined);
//        audioOnly.setEnabled(isJoined);
//        netType.setEnabled(isJoined);
    }

    int personCount;
    public void onPersonCount(int c)
    {
        personCount = c;
        if (onlineCount != null)
        {
            onlineCount.setText(String.valueOf(personCount));
        }
    }

    String titleStr;
    public void onTitle(String s)
    {
        titleStr = s;
        if(title != null)
            title.setText(titleStr);
    }

    public void setVideoViewVisible(boolean bVisible)
    {
        if (isAdded())
        {
            if (bVisible)
            {
                mGSViedoView.setVisibility(View.VISIBLE);
            } else
            {
                mGSViedoView.setVisibility(View.GONE);
            }
        }
    }

    public void onIdcList(List<PingEntity> arg0)
    {
        this.idcs = arg0;
    }

    boolean isAudioOnly;
    int handupState;

    @OnClick({R.id.exit, R.id.net_type, R.id.hand_up_parent, R.id.audio_only,
            R.id.full_screen, R.id.imvideoview})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.imvideoview:
                if (!isAnimGoing)
                {
                    if (isOperateVisiable)
                    {
                        toolbar.startAnimation(toolbarDisappearAnim);
                        rightOperate.startAnimation(rightbarDisappearAnim);
                        leftOperate.startAnimation(leftbarDisappearAnim);
                    } else
                    {
                        operate.setVisibility(View.VISIBLE);
                        toolbar.startAnimation(toolbarAppearAnim);
                        rightOperate.startAnimation(rightbarAppearAnim);
                        leftOperate.startAnimation(leftbarAppearAnim);
                    }
                }
                break;
            case R.id.exit:
                if (callback != null)
                    callback.onLiveExit();
                break;
            case R.id.hand_up_parent:
                if (handRun != null)
                {
                    txtHand.removeCallbacks(handRun);
                    handUp.setVisibility(View.VISIBLE);
                    txtHand.setVisibility(View.GONE);
                }
                if (handupState == 0)
                {
                    mPlayer.handUp(true, null);
                    txtHand.setVisibility(View.VISIBLE);
                    handUp.setVisibility(View.GONE);
                    handRun = new Runnable()
                    {
                        private int time = 60;

                        @Override
                        public void run()
                        {
                            handupState = 1;
                            txtHand.setText(String.valueOf(time));
                            time--;
                            if (time < 0)
                            {
                                handDown();
                            } else
                            {
                                txtHand.postDelayed(this, 1000);
                            }
                        }
                    };
                    txtHand.post(handRun);
                } else if(handupState == 1)
                {
                    handDown();
                    handupState = 0;
                }else if(handupState == 2)
                {
                    mPlayer.openMic(getActivity(), false, null);
                }
                break;
            case R.id.audio_only:
                if (mPlayer != null)
                {
                    if (!isAudioOnly)
                    {
                        mPlayer.videoSet(true);
                        isAudioOnly = true;
                        audioOnly.setImageResource(R.drawable.video_open);
                        audioOnlyHolder.setVisibility(View.VISIBLE);
                    } else
                    {
                        mPlayer.videoSet(false);
                        isAudioOnly = false;
                        audioOnly.setImageResource(R.drawable.video_close);
                        audioOnlyHolder.setVisibility(View.GONE);
                    }
                }
                break;
            case R.id.full_screen:
                if (callback != null)
                    callback.onLiveFullScreenClick();
                break;
            case R.id.net_type:
                int size = idcs == null ? 0 : idcs.size();
                if (size > 0)
                {
                    CharSequence[] sequences = new CharSequence[size];
                    String curIdc = mPlayer.getCurIdc();
                    int itemindex = -1;
                    for (int i = 0; i < size; i++)
                    {
                        sequences[i] = idcs.get(i).getName() + "(" + idcs.get(i).getDescription() + ")";
                        if (idcs.get(i).getIdcId().equals(curIdc))
                        {
                            itemindex = i;
                        }
                    }

                    alert(sequences, itemindex, new DialogInterface.OnClickListener()
                    {

                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            mPlayer.setIdcId(idcs.get(which).getCode(), null);
                            dialog.dismiss();
                        }
                    });
                }
                break;
        }
    }

    private Runnable handRun = null;

    private void handDown()
    {
        mPlayer.handUp(false, null);
        handUp.setVisibility(View.VISIBLE);
        txtHand.setVisibility(View.GONE);
    }

    public void onInviteResponse()
    {
        if (mPlayer != null)
        {
            mPlayer.openMic(mContext, true, null);
        }
    }

    public void onMicColesed()
    {
        handupState = 0;
        handUp.setVisibility(View.VISIBLE);
        handUp.setImageResource(R.drawable.hand_up);
        if (handRun != null)
        {
            txtHand.removeCallbacks(handRun);
            txtHand.setVisibility(View.GONE);
        }
    }

    public void onMicOpened(int inviteMediaType)
    {
        handupState = 2;
        handUp.setVisibility(View.VISIBLE);
        handUp.setImageResource(R.drawable.record_after);
        if (handRun != null)
        {
            txtHand.removeCallbacks(handRun);
            txtHand.setVisibility(View.GONE);
        }
//        txtMic.setTag(inviteMediaType);
//        txtMic.setVisibility(View.VISIBLE);
    }

    private List<PingEntity> idcs;

    private void alert(CharSequence[] items, int checkedItem, DialogInterface.OnClickListener listener)
    {
        new AlertDialog.Builder(getActivity()).setSingleChoiceItems(items, checkedItem, listener).create().show();
    }

    public void handleScreenOritention()
    {
        if (ScreenUtils.isPortrait(mContext))
        {
            fullScreen.setImageResource(R.drawable.full_screen);
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) parent.getLayoutParams();
            p.width = parentPortraitWidth;
            p.height = parentPortraitHeight;
            parent.setLayoutParams(p);

        } else
        {
            fullScreen.setImageResource(R.drawable.normal_screen);
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) parent.getLayoutParams();
            p.width = ScreenUtils.screenWidth(mContext);
            p.height = ScreenUtils.screenHeight(mContext);
            parent.setLayoutParams(p);
        }
    }

    /*public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.txtMic:
                if (mVodPlayer != null)
                {
                    mVodPlayer.openMic(getActivity(), false, null);
                    mVodPlayer.inviteAck((Integer) v.getTag(), false, null);
                }
                break;
            case R.id.txtHand:

                break;
            case R.id.txtIdc:
                int size = idcs == null ? 0 : idcs.size();
                if (size > 0)
                {
                    CharSequence[] sequences = new CharSequence[size];
                    String curIdc = mVodPlayer.getCurIdc();
                    int itemindex = -1;
                    for (int i = 0; i < size; i++)
                    {
                        sequences[i] = idcs.get(i).getName() + "(" + idcs.get(i).getDescription() + ")";
                        if (idcs.get(i).getIdcId().equals(curIdc))
                        {
                            itemindex = i;
                        }
                    }

                    alert(sequences, itemindex, new DialogInterface.OnClickListener()
                    {

                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            mVodPlayer.setIdcId(idcs.get(which).getCode(), null);
                            dialog.dismiss();
                        }
                    });
                }
                break;
        }
    }*/
}